#include <dirent.h>
#include <glib.h>
#include "libtiffanygirl.h"
#include "tiffanygirl_util.h"

gint strrncmp(const gchar *s1, const gchar *s2, gint len)
{
	gint i, n, offset;
	gchar *_s1;
	gchar *_s2;

	offset = strlen((char *)s1) - len;
	_s1 = s1 + offset;
	_s2 = s2;

	for (i=0;i<len;++i) {
		n = *(_s1+i) - *(_s2+i);

		if (n!=0)
			return n;
	}

	return 0;
}

gchar *tiffanygirl_new_filename_from_id(const gchar *id)
{
	gchar *filename;

	filename = g_strdup_printf("%36c.note", id);

	return filename;
}

gchar *tiffanygirl_new_id_from_filename(const gchar *filename)
{
	gchar id[37] = { NULL };

	sscanf(filename, "%36c.note", &id);

	return g_strdup(id); 
}

TGirl *tiffanygirl_new(void)
{
	TGirl *tgirl;

	tgirl = (TGirl *)g_new0(TGirl, 1);
	tgirl->dir_list = NULL;
	tgirl->note_list = NULL;

	return tgirl;
}

GList *tiffanygirl_scanning(TGirl *tgirl)
{
	TGirlNote *tgnote;
	struct dirent *file;
	DIR *dir;
	gchar *dirpath;
	gchar path[256];

	/* read tomboy's directory */
	dirpath = g_build_filename(g_get_home_dir(), ".tomboy", NULL);
	if ((dir=opendir(dirpath))==NULL)
		return;

	while((file=readdir(dir))) {
		if (*file->d_name=='.')
			continue;

		/* found note file */
		if (strrncmp(file->d_name, ".note", 5)==0) {
			sprintf(path, "%s/%s", dirpath, file->d_name);
			tgnote = tiffanygirl_note_new(tiffanygirl_new_id_from_filename(file->d_name), tiffanygirl_note_read_title(path));
			//printf("%s\n", tgnote->title);
			tgirl->note_list = g_list_append(tgirl->note_list, tgnote);
		}
	}

	closedir(dir);
	g_free(file);
	g_free(dirpath);
}
